package com.tju.welding.interceptor;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.tju.welding.utils.ApiResponse;
import com.tju.welding.utils.Code;

import org.springframework.web.servlet.HandlerInterceptor;

public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        if (request.getSession().getAttribute("user") != null) {
            return true;
        } else {
            ApiResponse apiResponse = ApiResponse.error(Code.LOGIN_ERROR);
            String content = JSON.toJSONString(apiResponse);
            write(request, response, content);
            return false;
        }
    }

    /**
     * 向 http responst 中写入json
     * 
     * @param request
     * @param response
     * @param content
     * @throws IOException
     */
    private void write(HttpServletRequest request, HttpServletResponse response, String content) throws IOException {

        String origin = request.getHeader("Origin");
        response.setHeader("Access-Control-Allow-Origin", origin);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        response.getWriter().write(content);

    }

}
